<?php
/**
 * Created by PhpStorm.
 * User: mr.houhai
 * Date: 2018/1/25
 * Time: 20:12
 */

namespace Xcx\Model;

class PraiseRecordModel extends BaseModel
{
    /**
     * 添加分享点赞记录
     * @param $pid
     * @return bool
     */
    public function addSharePraiseRecord($pid)
    {
        return $this->addRecord($pid,2,5);
    }

    /**
     * 添加用户点赞记录
     * @param $pid
     * @return bool
     */
    public function addUserPraiseRecord($pid)
    {
        return $this->addRecord($pid,1);
    }

    /**
     * 添加点赞数量
     * @param $pid
     * @param $type
     * @param $score
     * @return bool
     */
    public function addRecord($pid, $type, $score = 1)
    {
        //添加点赞记录
        $data['pid'] = $pid;
        $data['uid'] = $this->uid;
        $data['score'] = $score;
        $data['type'] = $type;
        $data['add_time'] = time();

        M()->startTrans();
        $res1 = $this->data($data)->add();
        //添加照片用户的点赞总数
        $res2 = $this->setIncAllPraiseCount($pid, $score);
        //添加照片被赞总数
        $Photo = new PhotoModel();
        $res3 = $Photo->setIncPraiseCount($pid, $score);

        if ($res1 && $res2 && $res3) {
            return true;
        } else {
            return false;
        }

    }

    /**
     * 增加照片墙用户被点赞总量
     * @param $pid
     * @return bool
     */
    private function setIncAllPraiseCount($pid, $score)
    {
        $Photo = new PhotoModel();
        $uid = $Photo->getUidByPid($pid);

        $User = new UsersModel();
        return $User->setIncAllPraiseCount($uid,$score);
    }

    /**
     * 获取点赞记录列表
     * @param $pid
     * @return array|string
     */
    public function getPraiseRecordList($pid)
    {
        $list = $this->alias('a')
            ->field('a.*,b.nickname,b.header')
            ->join('left join t_users b on a.uid = b.id')
            ->where(array('pid'=>$pid))
            ->order(array('add_time'=>'desc'))
            ->select();

        if (is_array($list) && count($list) > 0) {
            return getUploadImgDir($list,array('user_head'=>'header'));
        }
        return array();
    }

    /**
     * 检查用户是否有点赞记录
     * @param $pid
     * @return bool
     */
    public function checkUserIsPraise($pid)
    {
        $time = strtotime(date('Y-m-d',time()));
        $maps['pid'] = $pid;
        $maps['uid'] = $this->uid;
        $maps['type'] = 1;
        $maps['add_time'] = array('BETWEEN',array($time,$time + 24 * 3600));
        $res = $this->where($maps)->find();
        $sql = M()->getLastSql();
        if (is_array($res) && count($res) > 0) {
            return true;
        }
        return false;
    }
}